﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using ServBus.ListForm2010.Utility;
using ServBus.ListForm2010.Resources;
using System.Collections;
using System.Xml;

namespace ServBus.ListForm2010.Layouts.InfoBus2010
{
    public partial class ListFormManagement : LayoutsPageBase
    {
        private SPList mList;
        private SPWeb mWeb;
        private SPSite mSite;
        private InfoPathContext context;
        private string cTypeResrouceFolder;
        private string contentTypeName;
        private static DllResource Resource = new DllResource("ServBus.ListForm2010.Common.Resources|AppPages");

        protected void downloadFileClick(Exception ex)
        {
            LTException.Text = ex.ToString();
            errorPanel.Visible = true;
            ErrorLog.Write("ListFormInner" + "\r\n" + Request.Url + "\r\n" + ex.Message + "\r\n" + ex.StackTrace, System.Diagnostics.EventLogEntryType.Error);
        }

        #region Page

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!Page.IsPostBack)
                {
                    InitialData();
                }
            }
            catch (Exception ex)
            {
                downloadFileClick(ex);
            }
        }

        private bool InitialData()
        {
            bool initialStatus = false;
            if (!string.IsNullOrEmpty(Request["source"]))
            {
                okButton.Text = Resource.GetString("ListBus_Settings_BtnOK");
                okButton.Enabled = false;
                cancelButton.Text = Resource.GetString("ListBus_Settings_BtnCancel");
                ctDdl.Items.Clear();

                initialStatus = true;
                Guid _siteId = SPContext.Current.Site.ID;
                Guid _webId = SPContext.Current.Web.ID;

                Guid _listId = new Guid(Request["source"]);

                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite _site = new SPSite(_siteId))
                    {
                        using (SPWeb _web = _site.OpenWeb(_webId))
                        {
                            SPList _list = _web.Lists[_listId];

                            SPContentType _folderCType = _site.RootWeb.ContentTypes["Folder"];

                            for (int i = 0; i < _list.ContentTypes.Count; i++)
                            {
                                SPContentType _cType = _list.ContentTypes[i];
                                if (!_cType.Id.IsChildOf(_folderCType.Id))
                                {
                                    ctDdl.Items.Add(_cType.Name);
                                    if (ctDdl.Items.Count == 1) ctChanged(_cType.Name);
                                }
                            }
                        }
                    }
                });
            }

            return initialStatus;
        }

        protected void ctDdlChanged(object sender, EventArgs e)
        {
            try
            {
                contentTypeName = ctDdl.SelectedItem.Text;
                ctChanged(contentTypeName);
            }
            catch (Exception ex)
            {
                downloadFileClick(ex);
            }
        }

        protected void CreateFormRdChanged(object sender, EventArgs e)
        {
            okButton.Enabled = true;
        }

        protected void ModifyFormRdChanged(object sender, EventArgs e)
        {
            if (ModifyFormRd.Checked)
            {
                SpecificViewRd.Checked = false;
                dispViewDdl.Enabled = false;
                editViewDdl.Enabled = false;
                newViewDdl.Enabled = false;

                DefaultFormRd.Checked = false;
                deleteCB.Checked = false;
                deleteCB.Enabled = false;
                EditLookupStructure.Enabled = true;
            }
            okButton.Enabled = true;

        }

        protected void SpecificViewRdChanged(object sender, EventArgs e)
        {
            if (SpecificViewRd.Checked)
            {
                ModifyFormRd.Checked = false;
                EditLookupStructure.Checked = false;
                EditLookupStructure.Enabled = false;
                DefaultFormRd.Checked = false;
                deleteCB.Checked = false;
                deleteCB.Enabled = false;

                dispViewDdl.Enabled = true;
                editViewDdl.Enabled = true;
                newViewDdl.Enabled = true;
            }
            okButton.Enabled = true;

        }

        protected void DefaultFormRdChanged(object sender, EventArgs e)
        {
            if (DefaultFormRd.Checked)
            {
                SpecificViewRd.Checked = false;
                dispViewDdl.Enabled = false;
                editViewDdl.Enabled = false;
                newViewDdl.Enabled = false;

                ModifyFormRd.Checked = false;
                EditLookupStructure.Checked = false;
                EditLookupStructure.Enabled = false;
                deleteCB.Enabled = true;
            }
            okButton.Enabled = true;
        }

        protected void okButtonClick(object sender, EventArgs e)
        {
            try
            {
                if (CreateFormRd.Visible == true)
                {
                    if (CreateFormRd.SelectedValue == "1")
                    {
                        customizeForm();
                    }
                    if (CreateFormRd.SelectedValue == "2")
                    {
                        createLookupForm();
                    }
                }
                else
                {

                    if (ModifyFormRd.Checked)
                    {
                        if (EditLookupStructure.Checked)
                        {
                            createLookupForm();
                        }
                        else
                        {
                            modifyExistingForm();
                        }
                    }
                    else if (SpecificViewRd.Checked)
                    {
                        updateViewConfigItem();
                    }
                    else if (DefaultFormRd.Checked)
                    {
                        defaultForm();
                    }
                }
            }
            catch (Exception ex)
            {
                downloadFileClick(ex);
            }
        }

        protected void cancelButtonClick(object sender, EventArgs e)
        {
            Response.Write("<script type='text/javascript'>window.frameElement.commitPopup('ok');</script>");
        }

        private void ctChanged(string ctName)
        {
            try
            {
                if (!string.IsNullOrEmpty(ctName))
                {
                    okButton.Enabled = false;
                    Guid _siteId = SPContext.Current.Site.ID;
                    Guid _webId = SPContext.Current.Web.ID;
                    string _siteUrl = SPContext.Current.Site.Url;
                    Guid _listId = new Guid(Request["source"]);

                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        using (SPSite _site = new SPSite(_siteId))
                        {
                            using (SPWeb _web = Site.OpenWeb(_webId))
                            {
                                _web.AllowUnsafeUpdates = true;
                                SPList _list = _web.Lists[_listId];
                                SPContentType _cType = _list.ContentTypes[ctName];
                                SPFile xsnFile = null;
                                if (!isCustomizeFormExist(_siteUrl, _web, _list, _cType, ref xsnFile))
                                {
                                    modifyPanel.Visible = false;
                                    if (CreateFormRd.Items.Count != 2)
                                    {
                                        CreateFormRd.Items.Clear();
                                        ListItem item1 = new ListItem(Resource.GetString("ListBus_Settings_Customize"), "1");
                                        ListItem item2 = new ListItem(Resource.GetString("ListBus_Settings_LookupForm_Create"), "2");
                                        CreateFormRd.Items.Add(item1);
                                        CreateFormRd.Items.Add(item2);
                                    }
                                    CreateFormRd.Visible = true;
                                    //CustomizeFormRd.Text = Resource.GetString("ListBus_Settings_Customize");
                                    //CustomizeFormRd.Visible = true;
                                    //CreateLookupFormRd.Text = Resource.GetString("ListBus_Settings_LookupForm_Create");
                                    //CreateLookupFormRd.Visible = true;
                                }
                                else
                                {
                                    CreateFormRd.Visible = false;


                                    ModifyFormRd.Text = Resource.GetString("ListBus_Settings_Modify");
                                    ModifyFormRd.Checked = false;
                                    EditLookupStructure.Text = Resource.GetString("ListBus_Settings_LookupForm_Modify");
                                    EditLookupStructure.Checked = false;
                                    EditLookupStructure.Enabled = false;
                                    SpecificViewRd.Text = Resource.GetString("ListBus_Settings_SpecificViews");
                                    SpecificViewRd.Checked = false;
                                    DefaultFormRd.Text = Resource.GetString("ListBus_Settings_Default");
                                    DefaultFormRd.Checked = false;
                                    deleteCB.Text = Resource.GetString("ListBus_Settings_Delete");
                                    deleteCB.Checked = false;
                                    deleteCB.Enabled = false;

                                    dispViewDdl.Enabled = false;
                                    editViewDdl.Enabled = false;
                                    newViewDdl.Enabled = false;

                                    dispViewDdl.Items.Clear();
                                    editViewDdl.Items.Clear();
                                    newViewDdl.Items.Clear();
                                    string defalutView = "";
                                    List<string> views = getViews(xsnFile, ref defalutView);
                                    Dictionary<string, string> configViews = getViewConfigItem(_web, Convert.ToString(_listId), Convert.ToString(_cType.Id));
                                    bool configViewsExists = configViews.Count > 0;
                                    foreach (string formView in views)
                                    {
                                        string formViewId = formView.Substring(0, formView.IndexOf('_'));
                                        string formViewName = formView.Substring(formView.IndexOf('_') + 1);
                                        ListItem listItem1 = new ListItem(formViewName, formViewName);
                                        ListItem listItem2 = new ListItem(formViewName, formViewName);
                                        ListItem listItem3 = new ListItem(formViewName, formViewName);
                                        dispViewDdl.Items.Add(listItem1);
                                        editViewDdl.Items.Add(listItem2);
                                        newViewDdl.Items.Add(listItem3);
                                    }

                                    if (configViewsExists)
                                    {
                                        dispViewDdl.Items.FindByValue(configViews["DISP"]).Selected = true;
                                        editViewDdl.Items.FindByValue(configViews["EDIT"]).Selected = true;
                                        newViewDdl.Items.FindByValue(configViews["NEW"]).Selected = true;
                                    }
                                    else
                                    {
                                        dispViewDdl.Items.FindByValue(defalutView).Selected = true;
                                        editViewDdl.Items.FindByValue(defalutView).Selected = true;
                                        newViewDdl.Items.FindByValue(defalutView).Selected = true;
                                    }

                                    modifyPanel.Visible = true;

                                }
                            }
                        }
                    });
                }
            }
            catch (Exception ex)
            {
                downloadFileClick(ex);
            }
        }

        private List<string> getViews(SPFile file, ref string defautview)
        {
            List<string> views = new List<string>();
            byte[] xsnContent = null;

            xsnContent = file.OpenBinary();
            XmlDocument xsfDoc = new XmlDocument();
            XsnExtractor extractor = new XsnExtractor(xsnContent);
            byte[] xsfContent = extractor.Extract("manifest.xsf");
            using (MemoryStream xsfStream = new MemoryStream(xsfContent))
            {
                xsfDoc.Load(xsfStream);
            }

            // Validate Feature
            FeatureChecker checker = new FeatureChecker(xsfDoc);
            views = checker.ViewInfo;
            defautview = checker.DefaultView;
            return views;
        }

        #endregion

        #region Form Action

        private void modifyExistingForm()
        {
            try
            {
                string xsnLocation = "";
                contentTypeName = ctDdl.SelectedItem.Text;
                if (!string.IsNullOrEmpty(contentTypeName))
                {

                    Guid _siteId = SPContext.Current.Site.ID;
                    Guid _webId = SPContext.Current.Web.ID;
                    Guid _listId = new Guid(Request["source"]);
                    string _siteUrl = SPContext.Current.Site.Url;

                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        using (SPSite _site = new SPSite(_siteId))
                        {
                            using (SPWeb _web = Site.OpenWeb(_webId))
                            {
                                _web.AllowUnsafeUpdates = true;
                                SPList _list = _web.Lists[_listId];
                                SPContentType _cType = _list.ContentTypes[contentTypeName];

                                xsnLocation = _siteUrl + _cType.ResourceFolder.ServerRelativeUrl + "/template.xsn";
                            }
                        }
                    });
                }
                //Response.Write("<script type='text/javascript'>window.frameElement.commitPopup('Operation Successful!')</script>");

                Response.Write("<script type='text/javascript'>var spOpener = new ActiveXObject('SharePoint.OpenXMLDocuments');if (spOpener != null) {var x = spOpener.CustomizeTemplate('" + xsnLocation + "'); }window.frameElement.commitPopup('ok');</script>");
                //Response.Write("<script type='text/javascript'>var spOpener = new ActiveXObject('SharePoint.OpenXMLDocuments');if (spOpener != null) {var x = spOpener.CustomizeTemplate ('" + xsnLocation + "'); }</script>");

            }
            catch (Exception ex)
            {
                LTException.Text = ex.ToString();
                errorPanel.Visible = true;
            }
        }

        private void customizeForm()
        {
            try
            {
                string xsnLocation = "";
                string destFolderUrl = "";
                contentTypeName = ctDdl.SelectedItem.Text;
                string _siteUrl = SPContext.Current.Site.Url;
                if (!string.IsNullOrEmpty(contentTypeName))
                {

                    Guid _siteId = SPContext.Current.Site.ID;

                    Guid _webId = SPContext.Current.Web.ID;
                    Guid _listId = new Guid(Request["source"]);

                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        using (SPSite _site = new SPSite(_siteId))
                        {
                            using (SPWeb _web = Site.OpenWeb(_webId))
                            {
                                _web.AllowUnsafeUpdates = true;
                                SPList _list = _web.Lists[_listId];
                                SPContentType _cType = _list.ContentTypes[contentTypeName];
                                xsnLocation = _web.Url + "/" + _cType.ResourceFolder.Url + "/template.xsn";

                                if (!_web.GetFile(xsnLocation).Exists)
                                {
                                    //display_lb.aspx, edit_lb.aspx, new_lb.aspx
                                    destFolderUrl = _cType.ResourceFolder.ServerRelativeUrl;
                                    string listParameter = "listId=" + _list.ID.ToString();
                                    string cTypeParameter = "ctypeId=" + _cType.Id.ToString();
                                    string uploadFileName = Microsoft.SharePoint.Utilities.SPUtility.GetGenericSetupPath(@"TEMPLATE\LAYOUTS\InfoBus2010\Template.aspx");
                                    FileStream fileStream = File.Open(uploadFileName, FileMode.Open);
                                    _web.Files.Add(destFolderUrl + "/display_lb.aspx", fileStream, true);
                                    _cType.DisplayFormUrl = destFolderUrl + "/display_lb.aspx?" + listParameter + "%26" + cTypeParameter;
                                    _web.Files.Add(destFolderUrl + "/edit_lb.aspx", fileStream, true);
                                    _cType.EditFormUrl = destFolderUrl + "/edit_lb.aspx?" + listParameter + "%26" + cTypeParameter;
                                    _web.Files.Add(destFolderUrl + "/new_lb.aspx", fileStream, true);
                                    _cType.NewFormUrl = destFolderUrl + "/new_lb.aspx?" + listParameter + "%26" + cTypeParameter;

                                    RegisterEventReceiver(_list);

                                    fileStream.Close();
                                    _cType.Update();
                                    _list.Update();

                                    InitialContextVar(_siteUrl, _webId, _listId);
                                    cTypeResrouceFolder = _cType.ResourceFolder.Name;
                                    context.ListContentTypeName = _cType.Name;
                                    GenerateXSN();
                                }
                            }
                        }
                    });
                }

                Response.Write("<script type='text/javascript'>var spOpener = new ActiveXObject('SharePoint.OpenXMLDocuments');if (spOpener != null) {var x = spOpener.CustomizeTemplate('" + xsnLocation + "'); }window.frameElement.commitPopup('ok');</script>");

            }
            catch (Exception ex)
            {
                LTException.Text = ex.ToString();
                errorPanel.Visible = true;
            }
        }

        private void createLookupForm()
        {
            string redirectUrl = SPContext.Current.Web.Url + "/_layouts/InfoBus2010/LookupFormGenerator.aspx?source=" + Request["source"];
            redirectUrl += "&cType=" + ctDdl.SelectedItem.Text + "&IsDlg=1";
            Response.Redirect(redirectUrl);
        }

        private void defaultForm()
        {
            try
            {
                string xsnLocation = "";
                string destFolderUrl = "";
                contentTypeName = ctDdl.SelectedItem.Text;
                if (!string.IsNullOrEmpty(contentTypeName))
                {
                    Guid _siteId = SPContext.Current.Site.ID;
                    Guid _webId = SPContext.Current.Web.ID;
                    Guid _listId = new Guid(Request["source"]);

                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        using (SPSite _site = new SPSite(_siteId))
                        {
                            using (SPWeb _web = Site.OpenWeb(_webId))
                            {
                                _web.AllowUnsafeUpdates = true;
                                SPList _list = _web.Lists[_listId];
                                SPContentType _cType = _list.ContentTypes[contentTypeName];


                                _cType.DisplayFormUrl = _list.DefaultDisplayFormUrl;
                                _cType.EditFormUrl = _list.DefaultEditFormUrl;
                                _cType.NewFormUrl = _list.DefaultNewFormUrl;

                                _cType.Update();
                                UnBindingEventReceiver(_list);
                                _list.Update();

                                if (deleteCB.Checked)
                                {
                                    //display_lb.aspx, edit_lb.aspx, new_lb.aspx
                                    destFolderUrl = _web.Url + "/" + _cType.ResourceFolder.Url;
                                    xsnLocation = destFolderUrl + "/template.xsn";

                                    _web.GetFile(destFolderUrl + "/edit_lb.aspx").Delete();
                                    _web.GetFile(destFolderUrl + "/new_lb.aspx").Delete();
                                    _web.GetFile(destFolderUrl + "/display_lb.aspx").Delete();
                                    _web.GetFile(xsnLocation).Delete();
                                    deleteConfigItem(_web, Convert.ToString(_listId), Convert.ToString(_cType.Id));
                                }
                                _web.AllowUnsafeUpdates = false;
                            }
                        }
                    });
                }

                Response.Write("<script type='text/javascript'>window.frameElement.commitPopup('ok');</script>");


            }
            catch (Exception ex)
            {
                LTException.Text = ex.ToString();
                errorPanel.Visible = true;
            }
        }

        private void deleteConfigItem(SPWeb _web, string mListID, string mContentTypeID)
        {

            if (!string.IsNullOrEmpty(mListID) && !string.IsNullOrEmpty(mContentTypeID))
            {
                try
                {
                    SPList configList = _web.Lists[Constants.LookupForm_Config_NAME];
                    SPQuery query = new SPQuery();
                    query.Query = "<Where><And><Eq><FieldRef Name='Title' /><Value Type='Text'>" + mListID + "</Value></Eq><Eq><FieldRef Name='mContentType' /><Value Type='Text'>" + mContentTypeID + "</Value></Eq></And></Where>";
                    SPListItemCollection items = configList.GetItems(query);
                    ArrayList deletedList = new ArrayList();
                    foreach (SPListItem item in items)
                    {
                        deletedList.Add(item.ID);
                    }
                    foreach (int itemId in deletedList)
                    {
                        configList.Items.DeleteItemById(itemId);
                    }
                }
                catch { }
            }
        }

        private Dictionary<string, string> getViewConfigItem(SPWeb _web, string mListID, string mContentTypeID)
        {
            Dictionary<string, string> views = new Dictionary<string, string>();
            if (!string.IsNullOrEmpty(mListID) && !string.IsNullOrEmpty(mContentTypeID))
            {
                try
                {
                    SPList configList = _web.Lists[Constants.LookupForm_Config_NAME];
                    SPQuery query = new SPQuery();
                    query.Query = "<Where><And><Eq><FieldRef Name='Title' /><Value Type='Text'>" + mListID + "</Value></Eq><Eq><FieldRef Name='mContentType' /><Value Type='Text'>" + mContentTypeID + "</Value></Eq></And></Where>";
                    SPListItemCollection items = configList.GetItems(query);
                    if (items.Count > 0)
                    {
                        string dispView = Convert.ToString(items[0]["mDispView"]);
                        string editView = Convert.ToString(items[0]["mEditView"]);
                        string newView = Convert.ToString(items[0]["mNewView"]);

                        if (!string.IsNullOrEmpty(dispView))
                        {
                            views.Add("DISP", dispView);
                            views.Add("EDIT", editView);
                            views.Add("NEW", newView);
                        }

                    }
                }
                catch { }
            }
            return views;
        }

        private void updateViewConfigItem()
        {
            try
            {
                contentTypeName = ctDdl.SelectedItem.Text;
                if (!string.IsNullOrEmpty(contentTypeName))
                {
                    Guid _siteId = SPContext.Current.Site.ID;
                    Guid _webId = SPContext.Current.Web.ID;
                    Guid _listId = new Guid(Request["source"]);

                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        using (SPSite _site = new SPSite(_siteId))
                        {
                            using (SPWeb _web = Site.OpenWeb(_webId))
                            {
                                _web.AllowUnsafeUpdates = true;
                                SPList _list = _web.Lists[_listId];
                                SPContentType _cType = _list.ContentTypes[contentTypeName];

                                SPList configList = _web.Lists[Constants.LookupForm_Config_NAME];
                                SPQuery query = new SPQuery();
                                query.Query = "<Where><And><Eq><FieldRef Name='Title' /><Value Type='Text'>" + _listId + "</Value></Eq><Eq><FieldRef Name='mContentType' /><Value Type='Text'>" + _cType.Id + "</Value></Eq></And></Where>";
                                SPListItemCollection items = configList.GetItems(query);
                                if (items.Count > 0)
                                {
                                    SPListItem item = items[0];
                                    item["mDispView"] = dispViewDdl.SelectedValue;
                                    item["mEditView"] = editViewDdl.SelectedValue;
                                    item["mNewView"] = newViewDdl.SelectedValue;
                                    item.Update();
                                }
                                else
                                {
                                    SPListItem item = configList.Items.Add();
                                    item["Title"] = _listId;
                                    item["mContentType"] = _cType.Id;
                                    item["mDispView"] = dispViewDdl.SelectedValue;
                                    item["mEditView"] = editViewDdl.SelectedValue;
                                    item["mNewView"] = newViewDdl.SelectedValue;
                                    item.Update();
                                }
                                _web.AllowUnsafeUpdates = false;
                            }
                        }
                    });
                }

                Response.Write("<script type='text/javascript'>window.frameElement.commitPopup('ok');</script>");


            }
            catch (Exception ex)
            {
                LTException.Text = ex.ToString();
                errorPanel.Visible = true;
            }
        }

        #endregion

        #region GenerateXSN

        private void InitialContextVar(string _siteUrl, Guid _webId, Guid _listId)
        {
            if (context == null)
            {
                context = new InfoPathContext();
            }
            mSite = new SPSite(_siteUrl);
            // 101
            context.CurrentSiteUrl = _siteUrl;
            context.XsnName = "template";
            mWeb = mSite.OpenWeb(_webId);
            context.Web = mWeb;
            mList = mWeb.Lists[_listId];
            context.ListName = mList.Title;
            context.ListID = mList.ID.ToString();
            context.PageUrl = Context.Request.Url;
            context.MainListFullUrl = context.CurrentSiteUrl + mList.RootFolder.ServerRelativeUrl;
        }

        private bool isCustomizeFormExist(string _siteUrl, SPWeb web, SPList list, SPContentType CT, ref SPFile xsnFile)
        {
            string destFolderUrl = web.Url + "/" + CT.ResourceFolder.Url;
            string xsnLocation = destFolderUrl + "/template.xsn";
            if (web.GetFile(xsnLocation).Exists)
            {
                xsnFile = web.GetFile(xsnLocation);
                return true;
            }
            else return false;
        }
        private void GenerateXSN()
        {
            ListInfo keyListInfo = null;
            context.AddListNames(mList.Title);
            context.SelectedContent.Add(mList.Title, contentTypeName);
            keyListInfo = CreateListInfo(mList.Title, contentTypeName);

            context.XsnName = "template";

            //string subListName = "Contact";
            //context.AddedSecondaryListNames.Add(subListName);
            //ListInfo subListInfo = CreateSubListInfo(subListName, "Item");
            //keyListInfo.LookupLists.Add(subListInfo);

            StartCreateInfoPath(keyListInfo);
            UploadFileToFormLib();
        }

        private void UploadFileToFormLib()
        {
            try
            {
                System.Threading.Thread.Sleep(1000);
                // SPUtility.CreateFolderUnderList(mWeb,mList.Title,"defaultInfoPath");
                string xsnNam = context.XsnName + ".xsn";
                string m_xsn_location = SPUtility.CreateFile(Site, Web, mList, cTypeResrouceFolder, xsnNam, GetXsnFileStream());

                context.XsnLocation = m_xsn_location;
                //SPList list = Web.Lists[NameSpaceConstants.Name_FormLib];
                //SPUtility.CreateFileUnderDocLib(Web, list, xsnNam, GetXsnFileStream());
            }
            catch (Exception ex)
            {
                LTException.Text = ex.ToString();
                //File.WriteAllText(@"c:\a1.txt", ex.ToString());
                errorPanel.Visible = true;
            }
            //SPUtility.ClearAllItemsInFolder(mList, mList.RootFolder.SubFolders["defaultInfoPath"]);
            //Dictionary<string, string> dic = new Dictionary<string, string>();
            //dic.Add("Title", context.XsnName);
            //SPListItem item = SPUtility.CreateItemUnderFolder(mList, mList.RootFolder.SubFolders["defaultInfoPath"], dic);
            //SPUtility.AddFileToListItem(mList,item, context.XsnName + "_infoPath" + ".xsn", GetXsnFileStream());
            //string desPath = mWeb.Url + "/" + mList.Title + "/defaultInfoPath/" + context.XsnName + "_infoPath" + ".xsn";
            //SPUtility.UploadFileToDocumentLibrary(context.XsnPath, desPath);
        }

        private byte[] GetXsnFileStream()
        {
            byte[] buf = new byte[100];
            List<byte> bytes = new List<byte>();
            using (FileStream fs = File.Open(context.XsnPath, FileMode.Open, FileAccess.Read))
            {
                int offset = 0;
                int len = 0;
                while ((len = fs.Read(buf, offset, buf.Length)) > 0)
                {
                    CopyOneStreamToStream(buf, bytes);
                    buf = new byte[100];
                }
            }

            return bytes.ToArray();
        }

        private void CopyOneStreamToStream(byte[] byte1, List<byte> byte2)
        {
            foreach (byte bt in byte1)
            {
                byte2.Add(bt);
            }
        }

        private void StartCreateInfoPath(ListInfo listInfo)
        {
            //先初始化模板文件的根目录和目标文件的根目录
            string templateFilePath = Server.MapPath("/_layouts/InfoBus2010/template/");
            string destPath = Server.MapPath("/_layouts/InfoBus2010/TempXsnFiles/");
            NameSpaceConstants.TemplateRootPath = templateFilePath;
            if (!Directory.Exists(NameSpaceConstants.Des_Root_Path))
            {
                Directory.CreateDirectory(NameSpaceConstants.Des_Root_Path);
            }

            context.MainListFields = listInfo.Fields;
            CreateFieldLogic cl = new CreateFieldLogic(listInfo, context);
            cl.BeginToCreate();
        }

        private ListInfo CreateListInfo()
        {
            List<string> litNames = new List<string>();
            litNames.Add(mList.Title);
            ListInfo keyListInfo = null;

            context.AddListNames(mList.Title);
            string ctrid = CreateRadbtnID(mList.Title);
            string ctName = contentTypeName;

            context.SelectedContent.Add(mList.Title, ctName);
            keyListInfo = CreateListInfo(mList.Title, ctName);

            return keyListInfo;
        }

        private string CreateRadbtnID(string listTitle)
        {
            return string.Format("ctl00$PlaceHolderMain$sec{0}${0}##", listTitle);
        }

        private ListInfo CreateListInfo(string listTitle, string ctNam)
        {
            ListInfo listInfo = new ListInfo();
            listInfo.Name = listTitle;
            listInfo.Fields = new List<FieldInfo>();

            SPContentType ct = this.mWeb.Lists[listTitle].ContentTypes[ctNam];
            cTypeResrouceFolder = ct.ResourceFolder.Name;
            foreach (SPField fld in ct.Fields)
            {
                //TO DO..
                if (fld.StaticName == "ContentType")
                {
                    continue;
                }

                if (fld.ReadOnlyField || fld.Hidden)
                {
                    continue;
                }

                FieldInfo fldInfo = new FieldInfo();
                if (fld.Type.Equals(SPFieldType.Calculated))
                {
                    fldInfo.Hidden = true;
                }
                fldInfo.Required = fld.Required;
                listInfo.Fields.Add(fldInfo.CreateFieldInfo(fld, mList, ct));
            }

            // id field is a special, so we need to add it specific.
            SPField field = mList.Fields["ID"];
            FieldInfo idInfo = new FieldInfo();
            listInfo.Fields.Add(idInfo.CreateFieldInfo(field, mList, ct));
            return listInfo;
        }

        private ListInfo CreateSubListInfo(string listTitle, string ctNam)
        {
            ListInfo listInfo = new ListInfo();
            listInfo.Name = listTitle;
            listInfo.Fields = new List<FieldInfo>();

            SPContentType ct = this.mWeb.Lists[listTitle].ContentTypes[ctNam];
            foreach (SPField fld in ct.Fields)
            {
                //TO DO..
                if (fld.StaticName == "ContentType")
                {
                    continue;
                }
                FieldInfo fldInfo = new FieldInfo();
                if (fld.Type.Equals(SPFieldType.Calculated))
                {
                    fldInfo.Hidden = true;
                }
                fldInfo.Required = fld.Required;
                listInfo.Fields.Add(fldInfo.CreateFieldInfo(fld, mList, ct));
            }

            // id field is a special, so we need to add it specific.
            SPField field = mList.Fields["ID"];
            FieldInfo idInfo = new FieldInfo();
            listInfo.Fields.Add(idInfo.CreateFieldInfo(field, mList, ct));
            return listInfo;
        }
        #endregion

        #region RegisterEventReceiver

        private static void RegisterEventReceiver(SPList _list)
        {
            SPEventReceiverDefinition def1 = _list.EventReceivers.Add();
            def1.Assembly = "ServBus.ListForm2010, Version=1.0.0.0, Culture=Neutral, PublicKeyToken=df5827f77359eb0a";
            def1.Class = "ServBus.ListForm2010.SPFieldChangeEvent.SPFieldChangeEvent";
            def1.Type = SPEventReceiverType.FieldAdded;
            def1.Name = "SPFieldChangeEventFieldAdded";
            def1.Synchronization = SPEventReceiverSynchronization.Synchronous;
            def1.SequenceNumber = 1000;
            def1.Update();

            SPEventReceiverDefinition def2 = _list.EventReceivers.Add();
            def2.Assembly = "ServBus.ListForm2010, Version=1.0.0.0, Culture=Neutral, PublicKeyToken=df5827f77359eb0a";
            def2.Class = "ServBus.ListForm2010.SPFieldChangeEvent.SPFieldChangeEvent";
            def2.Type = SPEventReceiverType.FieldUpdated;
            def2.Name = "SPFieldChangeEventFieldUpdated";
            def2.Synchronization = SPEventReceiverSynchronization.Synchronous;
            def2.SequenceNumber = 1000;
            def2.Update();

            SPEventReceiverDefinition def3 = _list.EventReceivers.Add();
            def3.Assembly = "ServBus.ListForm2010, Version=1.0.0.0, Culture=Neutral, PublicKeyToken=df5827f77359eb0a";
            def3.Class = "ServBus.ListForm2010.SPFieldChangeEvent.SPFieldChangeEvent";
            def3.Type = SPEventReceiverType.FieldDeleting;
            def3.Name = "SPFieldChangeEventFieldDeleting";
            def3.Synchronization = SPEventReceiverSynchronization.Synchronous;
            def3.SequenceNumber = 1000;
            def3.Update();
        }

        private static void UnBindingEventReceiver(SPList _list)
        {
            List<string> eventReceiverList = new List<string>();
            eventReceiverList.Add("SPFieldChangeEventFieldAdded");
            eventReceiverList.Add("SPFieldChangeEventFieldUpdated");
            eventReceiverList.Add("SPFieldChangeEventFieldDeleting");
            for (int i = 0; i < _list.EventReceivers.Count; i++)
            {
                SPEventReceiverDefinition def = _list.EventReceivers[i];
                if (eventReceiverList.Contains(def.Name))
                {
                    def.Delete();
                    i--;
                }
            }
        }

        #endregion
    }
}
